/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package twitterWatchFollow;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import twitter4j.Twitter;
import twitter4j.TwitterException;

/**
 *
 * @author yos
 */
public class InformationJDialog extends javax.swing.JDialog {

    /**
     * Creates new form InformationJDialog
     */
    public InformationJDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea(){
            @Override
            public void append(String str){
                super.append(str);
                //jTextArea1.setCaretPosition(jTextArea1.getDocument().getLength());
            }
        };
        closejButton = new javax.swing.JButton();
        lastjButton = new javax.swing.JButton();
        topjButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setPreferredSize(new java.awt.Dimension(640, 300));

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        closejButton.setText("close");
        closejButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        closejButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closejButtonActionPerformed(evt);
            }
        });

        lastjButton.setText(">>");
        lastjButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                lastjButtonActionPerformed(evt);
            }
        });

        topjButton.setText("<<");
        topjButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                topjButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(topjButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lastjButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 250, Short.MAX_VALUE)
                .addComponent(closejButton)
                .addContainerGap())
            .addComponent(jScrollPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 269, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(closejButton)
                    .addComponent(lastjButton)
                    .addComponent(topjButton))
                .addGap(4, 4, 4))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void closejButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closejButtonActionPerformed
        setVisible(false);
    }//GEN-LAST:event_closejButtonActionPerformed

    private void lastjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lastjButtonActionPerformed
        jTextArea1.setCaretPosition(jTextArea1.getDocument().getLength());
    }//GEN-LAST:event_lastjButtonActionPerformed

    private void topjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_topjButtonActionPerformed
        jTextArea1.setCaretPosition(0);
    }//GEN-LAST:event_topjButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(InformationJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(InformationJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(InformationJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(InformationJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the dialog
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                InformationJDialog dialog = new InformationJDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    
    public void showFriendsFollowersRatioInCurrentXML(Twitter tw, javax.swing.JFrame parent) throws InterruptedException {
        xjcFollower.Root followerDocRoot = TwitterWatchFollow.m_followerHandler.getM_documentRoot();
        int friendsCount = followerDocRoot.getCurrentFriends().getUser().size();
        int followersCount = followerDocRoot.getCurrentFollowers().getUser().size();
        setTitle(String.format("%s's Firends Followers Status", TwitterWatchFollow.m_confHandler.getM_documentRoot().getUser()));
        double ffratio=((double) friendsCount) / followersCount;
        jTextArea1.append(String.format("pre-procedure: Friends/Followers = %d/%d = %.3f\n", friendsCount, followersCount, ffratio));
        //
        int friendsOnlyCount = 0;
        jTextArea1.append("Friends only:\n");
        for (xjcFollower.User taguser : followerDocRoot.getCurrentFriends().getUser()) {
            // friend - follow relationship
            if (!TwitterCommon.isDuplicatedUserIdInXMLUserList(taguser.getValue(), followerDocRoot.getCurrentFollowers().getUser())) {
                ++friendsOnlyCount;
                jTextArea1.append(String.format("\t%d %s (%s)\n", taguser.getValue(), taguser.getName(), taguser.getScreenName()));
            }
        }
        //
        int followersOnlyCount = 0;
        jTextArea1.append("Followers only:\n");
        for (xjcFollower.User taguser : followerDocRoot.getCurrentFollowers().getUser()) {
            // follow - friendrelationship
            if (!TwitterCommon.isDuplicatedUserIdInXMLUserList(taguser.getValue(), followerDocRoot.getCurrentFriends().getUser())) {
                ++followersOnlyCount;
                jTextArea1.append(String.format("\t%d %s (%s)\n", taguser.getValue(), taguser.getName(), taguser.getScreenName()));
            }
        }
        jTextArea1.append(String.format("  summary of friends only : followers only = %d : %d\n", friendsOnlyCount, followersOnlyCount));
        //
        int canditExpiredFriendsCount = 0;
        int expiredFriendsCount = 0;
        jTextArea1.append("Expired Friends:\n");
        if(ffratio<TwitterWatchFollow.m_act_destoroy_ffratio){
            jTextArea1.append(String.format("\tskipped because friends/followers ratio is low (<%.2f).\n",TwitterWatchFollow.m_act_destoroy_ffratio));
        }else{
            GregorianCalendar gc = new GregorianCalendar();
            gc.setTime(Calendar.getInstance().getTime());
            gc.add(GregorianCalendar.DAY_OF_MONTH, -TwitterWatchFollow.m_expire_days);
            //
            List<xjcFollower.User> removeCanditList=new ArrayList<>();
            try {
                XMLGregorianCalendar xmlgc = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
                //
                for(xjcFollower.User watchuser : followerDocRoot.getWatchDog().getUser()){
                    if(watchuser.getDate().compare(xmlgc)<0){
                        if(TwitterCommon.isDuplicatedUserIdInXMLUserList(watchuser.getValue(), followerDocRoot.getKeep().getUser())){
                            jTextArea1.append(String.format("\t(KEEP) %d %s (%s) %s\n",watchuser.getValue(),watchuser.getName(),watchuser.getScreenName(),watchuser.getDate()));
                        }else{
                            ++canditExpiredFriendsCount;
                            jTextArea1.append(String.format("\t%d %s (%s) %s\n",watchuser.getValue(),watchuser.getName(),watchuser.getScreenName(),watchuser.getDate()));
                            removeCanditList.add(watchuser);
                        }
                    }
                }
                //
                for(xjcFollower.User removeUser : removeCanditList){
                    try {
                        tw.destroyFriendship(removeUser.getValue());
                        ++expiredFriendsCount;
                        followerDocRoot.getRejected().getUser().add(removeUser);
                        followerDocRoot.getWatchDog().getUser().remove(removeUser);
                    } catch (TwitterException ex) {
                        if(!TwitterCommon.sleepUntilRateLimitReset(ex, parent)){
                            continue;
                        }else if(ex.getStatusCode()==404){
                            jTextArea1.append(String.format("Already Resign From Twitter %d %s (%s) %s. Moved to rejected\n",removeUser.getValue(),removeUser.getName(),removeUser.getScreenName(),removeUser.getDate()));
                            ++expiredFriendsCount;
                            followerDocRoot.getRejected().getUser().add(removeUser);
                            followerDocRoot.getWatchDog().getUser().remove(removeUser);
                            continue;                            
                        }else{
                            Logger.getLogger(InformationJDialog.class.getName()).log(Level.SEVERE, null, ex);
                            break;
                        }
                    }
                }
            } catch (DatatypeConfigurationException ex) {
                Logger.getLogger(InformationJDialog.class.getName()).log(Level.SEVERE, null, ex);
            }
            // -keep
            jTextArea1.append(String.format("  summary of candidate expired friends : expired = %d : %d\n", canditExpiredFriendsCount, expiredFriendsCount));
        }
    }
        
        
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton closejButton;
    private javax.swing.JScrollPane jScrollPane1;
    public javax.swing.JTextArea jTextArea1;
    private javax.swing.JButton lastjButton;
    private javax.swing.JButton topjButton;
    // End of variables declaration//GEN-END:variables
}
